package com.sk.weichat.fragment;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.sk.weichat.AppConstant;
import com.sk.weichat.R;
import com.sk.weichat.bean.User;
import com.sk.weichat.db.InternationalizationHelper;
import com.sk.weichat.db.dao.UserDao;
import com.sk.weichat.helper.AvatarHelper;
import com.sk.weichat.ui.MainActivity;
import com.sk.weichat.ui.account.MultiAccountActivity;
import com.sk.weichat.ui.base.CoreManager;
import com.sk.weichat.ui.base.EasyFragment;
import com.sk.weichat.ui.circle.PublishDynamicActivity;
import com.sk.weichat.ui.circle.range.SendVideoActivity;
import com.sk.weichat.ui.me.MyCollectionActivity;
import com.sk.weichat.ui.me.PersonalCenterActivity;
import com.sk.weichat.ui.me.SettingActivity;
import com.sk.weichat.ui.me.wallet.MyWalletActivity;
import com.sk.weichat.ui.message.TabFriendActivity;
import com.sk.weichat.ui.other.QRcodeActivity;
import com.sk.weichat.ui.tool.SingleImagePreviewActivity;
import com.sk.weichat.ui.tool.WebViewActivity;
import com.sk.weichat.util.SystemUtil;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.util.UiUtils;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;

import java.util.HashMap;

import okhttp3.Call;

import static com.sk.weichat.ui.tool.WebViewActivity.EXTRA_URL;

//@RuntimePermissions
public class MeFragment extends EasyFragment implements View.OnClickListener {

    private ImageView mAvatarImg;
    private TextView mNickNameTv;
    private TextView mAccountTv;
    private TextView setTv;

    public static final int REQUEST_CIRCLE_BG_CHANGE = 101;
    public static final int requestCode_camera = 2783;
    private TextView mTvFriendCount;
    private TextView mTvAttentionCount;
    private TextView mTvFansCount;
    private TextView mTvGroupsCount;

    public MeFragment() {
    }

    @Override
    protected int inflateLayoutId() {
        return R.layout.fragment_me;
    }

    @Override
    protected void onActivityCreated(Bundle savedInstanceState, boolean createView) {
        if (createView) {
            initView();
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && coreManager != null) {
            mAccountTv.setText("悦聊号：" + coreManager.getSelf().getAccount());
            mNickNameTv.setText(coreManager.getSelf().getNickName());
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        updateUI();
    }

    private void initView() {
        setTv = (TextView) findViewById(R.id.SettingTv);
        setTv.setText(InternationalizationHelper.getString("JXSettingVC_Set"));
        findViewById(R.id.layout_me_info).setOnClickListener(this);
        findViewById(R.id.img_center_copy).setOnClickListener(this);
        findViewById(R.id.my_collection_tv).setOnClickListener(this);
        findViewById(R.id.my_wallet_rl).setOnClickListener(this);
        findViewById(R.id.layout_me_qrcode).setOnClickListener(this);
        findViewById(R.id.layout_scanning).setOnClickListener(this);
        findViewById(R.id.setting_rl).setOnClickListener(this);

        findViewById(R.id.layout_me_friend).setOnClickListener(this);
        findViewById(R.id.layout_me_attention).setOnClickListener(this);
        findViewById(R.id.layout_me_fans).setOnClickListener(this);
        findViewById(R.id.layout_me_groups).setOnClickListener(this);
        findViewById(R.id.rl_sfeedback_app).setOnClickListener(this);
        //多账号切换
        findViewById(R.id.tv_multi_account).setOnClickListener(this);

        mAvatarImg = (ImageView) findViewById(R.id.avatar_img);
        mNickNameTv = (TextView) findViewById(R.id.nick_name_tv);
        mAccountTv = (TextView) findViewById(R.id.account_number_tv);
        mTvFriendCount = (TextView) findViewById(R.id.tv_me_friend);
        mTvAttentionCount = (TextView) findViewById(R.id.tv_me_attention);
        mTvFansCount = (TextView) findViewById(R.id.tv_me_fans);
        mTvGroupsCount = (TextView) findViewById(R.id.tv_me_groups);


        AvatarHelper.getInstance().displayAvatar(coreManager.getSelf().getNickName(), coreManager.getSelf().getUserId(), mAvatarImg, false);
        mNickNameTv.setText(coreManager.getSelf().getNickName());
        mTvFriendCount.setText(coreManager.getSelf().getFriendsCount() + "");
        mTvAttentionCount.setText(coreManager.getSelf().getAttCount() + "");
        mTvFansCount.setText(coreManager.getSelf().getFansCount() + "");
        mTvGroupsCount.setText(coreManager.getSelf().getRoomCount() + "");

        mAvatarImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), SingleImagePreviewActivity.class);
                intent.putExtra(AppConstant.EXTRA_IMAGE_URI, coreManager.getSelf().getUserId());
                startActivity(intent);
            }
        });

        initTitleBackground();
        TextView shareAppTv = findViewById(R.id.tv_share_app);
        shareAppTv.setText(getString(R.string.share_app, getString(R.string.app_name)));
        findViewById(R.id.rl_share_app).setOnClickListener(v -> {
            Intent shareIntent = new Intent();
            shareIntent.setAction(Intent.ACTION_SEND);
            shareIntent.setType("text/plain");
            shareIntent.setAction(Intent.ACTION_SEND);
            shareIntent.putExtra(Intent.EXTRA_TEXT, getString(R.string.sms_content, coreManager.getSelf().getAccount())
                    + coreManager.getConfig().website);
            shareIntent = Intent.createChooser(shareIntent, getString(R.string.sms_content, coreManager.getSelf().getAccount())
                    + coreManager.getConfig().website);
            startActivity(shareIntent);
        });
    }

    private void initTitleBackground() {
//        SkinUtils.Skin skin = SkinUtils.getSkin(requireContext());
//        int primaryColor = skin.getPrimaryColor();
//        findViewById(R.id.tool_bar).setBackgroundColor(primaryColor);
//        findViewById(R.id.tool_bar).setBackgroundResource(R.drawable.grzx_bg);
    }

    @Override
    public void onClick(View v) {
        if (!UiUtils.isNormalClick(v)) {
            return;
        }
        Intent intent;
        int id = v.getId();
        switch (id) {
            case R.id.layout_me_info:
                // 我的资料
                intent = new Intent(getActivity(), PersonalCenterActivity.class);
                intent.putExtra(AppConstant.EXTRA_USER_ID, coreManager.getSelf().getUserId());
                startActivityForResult(intent, 1);
                break;

            case R.id.layout_me_friend:
                intent = new Intent(getActivity(), TabFriendActivity.class);
                intent.putExtra("tabPosition", 0);
                startActivity(intent);
                break;
            case R.id.layout_me_attention:
                intent = new Intent(getActivity(), TabFriendActivity.class);
                intent.putExtra("tabPosition", 1);
                startActivity(intent);
                break;
            case R.id.layout_me_fans:
                intent = new Intent(getActivity(), TabFriendActivity.class);
                intent.putExtra("tabPosition", 2);
                startActivity(intent);
                break;
            case R.id.layout_me_groups:
                intent = new Intent(getActivity(), TabFriendActivity.class);
                intent.putExtra("tabPosition", 3);
                startActivity(intent);
                break;

            case R.id.img_center_copy:
                // 复制
                SystemUtil.copyText(getActivity().getApplicationContext(), mAccountTv.getText().toString());
                ToastUtil.showToast(getContext(), "复制成功");
                break;

            case R.id.my_collection_tv:
                // 我的收藏
//                startActivity(new Intent(getActivity(), MyCollectionActivity.class));
                startActivity(new Intent(getActivity(), SendVideoActivity.class));


                break;
            case R.id.my_wallet_rl:
                // 钱包
                startActivity(new Intent(getActivity(), MyWalletActivity.class));
                break;
            case R.id.layout_scanning:
                if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                    // 扫一扫
                    openScanQRCode();
                } else {
                    requestPermissions(new String[]{Manifest.permission.CAMERA}, requestCode_camera);
                }
                break;
            case R.id.layout_me_qrcode:
                // 二维码名片
                intent = new Intent(getActivity(), QRcodeActivity.class);
                intent.putExtra("isgroup", false);
                intent.putExtra("userid", coreManager.getSelf().getUserId());
                startActivity(intent);
                break;
            case R.id.rl_sfeedback_app:
                //意见反馈
                intent = new Intent(getActivity(), WebViewActivity.class);
                intent.putExtra(EXTRA_URL, coreManager.getConfig().FEEDBACK_URL + "?access_token=" + CoreManager.requireSelfStatus(getContext()).accessToken);
                intent.putExtra("feedback", true);
                startActivity(intent);

                break;
            case R.id.setting_rl:
                // 设置
                startActivity(new Intent(getActivity(), SettingActivity.class));
                break;


            case R.id.tv_multi_account:
                // 多账号切换
                startActivity(new Intent(getActivity(), MultiAccountActivity.class));
                break;
        }
    }

    //@NeedsPermission(Manifest.permission.CAMERA)
    public void openScanQRCode() {
        MainActivity.requestQrCodeScan(getActivity());
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == requestCode_camera && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            openScanQRCode();
        } else {
            ToastUtil.showToast(getActivity(), "相机权限被拒绝");
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 || resultCode == Activity.RESULT_OK) {// 个人资料更新了
            updateUI();
        }
    }

    /**
     * 用户的信息更改的时候，ui更新
     */
    private void updateUI() {
        if (mAvatarImg != null) {
            AvatarHelper.getInstance().displayAvatar(coreManager.getSelf().getUserId(), mAvatarImg, false);
        }
        if (mNickNameTv != null) {
            mNickNameTv.setText(coreManager.getSelf().getNickName());
        }

        //下载个人基本资料
        downloadUserInfo();

//        AsyncUtils.doAsync(this, t -> {
//            Reporter.post("获取好友数量失败，", t);
//            if (getActivity() != null) {
//                getActivity().runOnUiThread(() -> {
//                    ToastUtil.showToast(requireContext(), R.string.tip_me_query_friend_failed);
//                });
//            }
//        }, ctx -> {
//            long count = FriendDao.getInstance().getFriendsCount(coreManager.getSelf().getUserId());
//            ctx.uiThread(ref -> {
//
//            });
//        });
//
//        AsyncUtils.doAsync(this, t -> {
//            Reporter.post("获取群组数量失败，", t);
//            if (getActivity() != null) {
//                getActivity().runOnUiThread(() -> {
//                    ToastUtil.showToast(requireContext(), R.string.tip_me_query_friend_failed);
//                });
//            }
//        }, ctx -> {
//            long count = FriendDao.getInstance().getGroupsCount(coreManager.getSelf().getUserId());
//            ctx.uiThread(ref -> {
//
//            });
//        });

    }

    /**
     * 下载个人基本资料
     */
    private void downloadUserInfo() {
        HashMap<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);

        HttpUtils.get().url(coreManager.getConfig().USER_GET_URL)
                .params(params)
                .build()
                .execute(new BaseCallback<User>(User.class) {

                    @Override
                    public void onResponse(ObjectResult<User> result) {
                        boolean updateSuccess = false;
                        if (result.getResultCode() == 1) {
                            User user = result.getData();
                            user.setIsQQBand(TextUtils.isEmpty(user.getQqUser().getNickname()) ? 0 : 1);
                            user.setQqNickName(TextUtils.isEmpty(user.getQqUser().getNickname()) ? "" : user.getQqUser().getNickname());

                            user.setIsWXBand(TextUtils.isEmpty(user.getWxUser().getNickname()) ? 0 : 1);
                            user.setWxNikeName(TextUtils.isEmpty(user.getWxUser().getNickname()) ? "" : user.getWxUser().getNickname());
                            updateSuccess = UserDao.getInstance().updateByUser(user);
                            // 设置登录用户信息
                            if (updateSuccess) {
                                // 如果成功，保存User变量，
                                coreManager.setSelf(user);
                                mAccountTv.setText("悦聊号：" + user.getAccount());
                                mNickNameTv.setText(user.getNickName());
                                mTvFriendCount.setText(coreManager.getSelf().getFriendsCount() + "");
                                mTvAttentionCount.setText(coreManager.getSelf().getAttCount() + "");
                                mTvFansCount.setText(coreManager.getSelf().getFansCount() + "");
                                mTvGroupsCount.setText(coreManager.getSelf().getRoomCount() + "");
                            }
                        }

                    }

                    @Override
                    public void onError(Call call, Exception e) {

                    }
                });
    }

    public void onNewIntentRefresh() {
        Log.e("lzs", "MeFragment onNewIntentRefresh");
        updateUI();
    }
}
